package com.lv.service.impl;

import com.lv.pojo.TbGoods;
import com.lv.pojo.TbGoodsDesc;
import com.lv.pojo.TbItem;
import com.lv.service.GoodsDescService;
import com.lv.service.GoodsService;
import com.lv.service.ItemPageService;
import com.lv.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemPageServiceImpl implements ItemPageService {

    @Autowired
    private FreeMarkerConfigurer freemarker;

    @DubboReference
    private GoodsService gs;

    @DubboReference
    private GoodsDescService ds;

    @DubboReference
    private ItemService is;

    @Override
    public void createPage(Long goodsId) {
        //创建配置对象
        Configuration configuration = freemarker.getConfiguration();
        Template template = null;
        FileWriter writer = null;
        try {

            //获取模板对象
            template = configuration.getTemplate("item.ftl");


            //查数据
            TbGoods goods = gs.getGoodsById( goodsId);
            TbGoodsDesc desc = ds.getGoodsDescById( goodsId);
            List<TbItem> list = is.selectItemListByGoodsId(goodsId);

            //创建模板对象所需的数据
            Map<String,Object> map = new HashMap();
            map.put("goods",goods);
            map.put("desc",desc);
            map.put("item",list);


            //创建输出对象,并指定输出位置
            writer = new FileWriter("F:\\吕品\\java_4\\dd_shop_freemarker\\" + goodsId + ".html");
            //调用模板对象输出
            template.process(map, writer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                if (writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
